/* Change this if the SERVER_NAME environment variable does not report
	the true name of your web server. */
#if 1
#define SERVER_NAME cgiServerName
#endif
#if 0
#define SERVER_NAME "www.mizss.com"
#endif


#ifdef WIN32
#define SAVED_ENVIRONMENT "c:\\cgicsave.env"
#else
#define SAVED_ENVIRONMENT "/tmp/cgicsave.env"
#endif /* WIN32 */
#define CGICDEBUG 1
#include <stdio.h>
#include<stdlib.h>
#include "md5.h"
#include "cgic.h"
#include "cJSON.h"
#include <string.h>
#include "common.h"
#include "session.h"
#include <sqlite3.h>

static sqlite3 *db;
int offset = 0;
struct User
{
    int  id;
    char username[16];
    char password[33];
    int type;
};

void router();
int  loginAuth();
int  checkLoginState();

int  demo();
int initDb();
int callback(void *para, int f_num, char *f_value[], char *f_name[]);
int Msg(int ret,const char* msg);
//cJSON* getNodeJson(const char*);

int cgiMain() {

    //开启会话
	session_start("/tmp/");
    initDb();
    //demo();
    if(checkLoginState()==0){
        demo();
    }else{
        loginAuth();
    }
    //销毁会话
    sqlite3_close(db);

    session_write_close();
	
	
	return 0;
}
//登录授权
int  loginAuth(){
    struct User user[10];
    char *errmsg;
    char select[]="select * from user where username='%s';";
    
    cgiHeaderContentType("application/json");

    //从缓冲区中解析出JSON结构
    cJSON *root = cJSON_Parse(cgiRequestionBody);

    if (root == NULL)
    {
        Msg(1,"数据格式非法！");
        return 0;
    }
    cJSON *item = cJSON_GetObjectItem(root,"username");
    if (item == NULL)
    {
        Msg(1,"数据格式非法！");
        return 0;
    }
    char username[16],password[33];
    memcpy(username,item->valuestring,strlen(item->valuestring));
    item = cJSON_GetObjectItem(root,"password");
    if (item == NULL)
    {
        Msg(1,"数据格式非法！");
        return 0;
    }
    memcpy(password,item->valuestring,strlen(item->valuestring));
    cJSON_Delete(root);
    char sql[512];
    sprintf(sql,select,username);

    //取出用户信息
    if(sqlite3_exec(db,sql,callback,(void*)&user,&errmsg)!=0)
    {   
        //fprintf(cgiOut,"debug:%s\n",errmsg);
        Msg(1,errmsg);
        return 0;
    }

    if (offset==0){
        return 0;
    }
    char* buffer = (char*)malloc(33 * sizeof(char));
    memset(buffer, 0, 33 * sizeof(char));
    MD5Data(password, strlen(password), buffer);

    if(strcmp(user[0].password,buffer)==0){
        cgiHeaderCookieSetString("isLogin", "1", 900, "/", cgiServerName);
        session_set("isLogin", "1");
        Msg(0,"登录成功");
    }
    return 0;
}
int demo(){
    cgiHeaderContentType("application/json");

    char *char_json = "{\"hello\":\"你好\" }";

    //从缓冲区中解析出JSON结构
    cJSON *json = cJSON_Parse(char_json);

    if (json == NULL)
    {
        return 0;
    }

    //将传入的JSON结构转化为字符串 
    char *buf = NULL;
     buf = cJSON_PrintUnformatted(json);
	CGI_ECHO(buf);
    free(buf);//释放资源
    cJSON_Delete(json);//释放资源
    
    struct User user[10];
    char *errmsg;
    char select[]="select * from user where username='admin';";
    

    if(sqlite3_exec(db,select,callback,(void*)&user,&errmsg)!=0)
    {   
        fprintf(cgiOut,"debug:%s\n",errmsg);
    }
    //CGI_ECHO("debug");
    //sqlite3_sleep(3000);
    fprintf(cgiOut,"xxxx%d\n",offset);

    int i =0;
    
    for(i=0;i<offset;i++)
    {
       //CGI_ECHO(user[i].username);
        fprintf(cgiOut,"%d\t%s\t%s\t%d\n",user[i].id,user[i].username,user[i].password,user[i].type);
 
    }


    if(!strcmp(cgiRequestMethod,"POST")){
            CGI_ECHO(cgiContentType);
            CGI_ECHO(cgiRequestionBody); 

    }

    return 0;
}
//初始化数据库连接
int initDb(){
    if(sqlite3_open("/Volumes/dataExt/work/project/AI/demo/boa/examples/www/cgi-bin/data.db",&db)!=0)
    { 
        CGI_ECHO("cannot open database");
    }

}

int checkLoginState(){
    

    //int result;
    char *status = NULL;
    //result = cgiCookieString("isLogin",status, 1);
    
    status = session_get("isLogin");
    if(status == NULL){
         //cgiHeaderContentType("application/json");
        // Msg(1,"data is faild!");
         return -1;
    }
    if(strcmp(status,"1")!= 0){
       // cgiHeaderContentType("application/json");
       // Msg(1,"data is faild!");
        return -1;

    }

    //exit(0);
    return 0;
}

int callback(void *para, int f_num, char *f_value[], char *f_name[])
{
    int i;
    struct User *p = (struct User*)para+offset;
    p->id = atoi(f_value[0]);
    strcpy(p->username,f_value[1]);
    strcpy(p->password,f_value[2]);
    p->type = atoi(f_value[3]);
    offset++;//每次回调函数执行offset加1
    return 0;
}
int Msg(int ret,const char* msg){
    cJSON*root=cJSON_CreateObject();
    cJSON*item=cJSON_CreateNumber(ret);
    cJSON_AddItemToObject(root,"ret",item);

    item=cJSON_CreateString(msg);
    cJSON_AddItemToObject(root,"msg",item);

    char *buf = NULL;
    buf = cJSON_PrintUnformatted(root);
	CGI_ECHO(buf);
    free(buf);//释放资源
    cJSON_Delete(root);//释放资源
    return 0;
}